package com.cc.servlet;

import com.alibaba.fastjson.JSON;
import com.cc.entity.Oss;
import com.cc.service.Impl.OssServiceImpl;
import com.cc.service.OssService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(name = "OssServlet",urlPatterns = "/oss.action" )
public class OssServlet extends HttpServlet {
    OssService ossService = new OssServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String opr = (request.getParameter("opr")==null||"".equals(request.getParameter("opr")))
                ?"list":request.getParameter( "opr");

        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("utf-8");
        switch (opr){
            case"list":
                List<Oss> ossList = ossService.selectAll();
                String json = JSON.toJSONString(ossList);
                response.getWriter().print(json);
                return;
            case"add":
                String bucketName = request.getParameter("bucketName");
                String type = request.getParameter("type");
                String permission = request.getParameter("permission");
                Oss oss = new Oss();
                oss.setBucketName(bucketName);
                oss.setType(type);
                oss.setPermission(permission);
                boolean flag = ossService.add(oss);
                Map map = new HashMap();
                if (flag) {
                    map.put("code", "ok");
                } else {
                    map.put("code", "error");
                }
                response.getWriter().print(JSON.toJSONString(map));
                return;
            case "update":
                String bucketName1 = request.getParameter("id");
                String permission1 = request.getParameter("permission");
                boolean updateOss = ossService.updateOss(bucketName1,permission1);
                String json2 = JSON.toJSONString(updateOss);
                response.getWriter().print(json2);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
